/**
 * Created by vincent on 16-4-22.
 */
'use strict';

var params = {};
var tempArray = window.location.search.split('?');
if (tempArray.length == 2) {
    var parts = tempArray[1].split('&');
    for (var i = 0; i < parts.length; i++) {
        var nv = parts[i].split('=');
        if (!nv[0]) continue;
        params[nv[0]] = nv[1] || true;
    }
}


var detailApp = angular.module('publicDetailApp', ['ngRoute', 'ngResource', 'marketFilters']);
//var host = 'localhost:3000';
/*var host = 't.app.66xiaoqu.com';*/
/*  宝宝树66小区二次改造    mod   dayu  20170724   start   */
var host = 'app-66xiaoqu.babytree.com';
//var host = 'app.h2oprint.com';
/*  宝宝树66小区二次改造    mod   dayu  20170724   end   */
//var host = "192.168.1.26:3000";

var h5Host = host.replace('app', 'h5');
var resHost = host.replace('app', 'img');
if (host.indexOf('t') >= 0) {
    resHost = host.replace('app', 'res');
}
//var detailShareUrl = 'http://' + h5Host + '/app/share/share_detail.html?token=' + params.token + '&goodsId=' + params.goodsId;

function showImage(images, index) {
    var type = params.type;
    if (type == 'android') {
        webviewhandle.showImage(images, index);//webviewhandle为webview注册对象
    } else {
        var vCode = params.vcode;
        if (vCode != null && parseInt(vCode) > 200033) {
            document.location.href = "66xiaoqu:showImage##images=" + images + "&nbsp;index=" + index;
        }
    }
}

detailApp.controller('GoodsDetailCtrl', ['$scope', '$http', 'GoodsDetail', 'ReplyList',
    function ($scope, $http, GoodsDetail, ReplyList) {
        $('.swiper-wrapper').attr('style', 'height: ' + $(document.body).width() + 'px;');
        $('.swiper-container').attr('style', 'height: ' + $(document.body).width() + 'px;');

        var type = params.type;

        $scope.itemTypeWord = {1:'闲置',2:"服务"};

        GoodsDetail.get(function (result) {
                $scope.nickName = result.data.createdBy.nickName;
                $scope.communityName = result.data.community.communityName;
                $scope.detail = result.data;
                $scope.headImg = result.data.createdBy.images[0].imageURL;

                var dealStatus = $scope.detail.dealStatus;

                var sharePic = "";
                if (result.data.images != null && result.data.images.length > 0) {
                    sharePic = result.data.images[0].imageURL;
                }

                var shareTitle = $scope.detail.title;
                var shareDesc = $scope.detail.desc;

                if ($scope.detail.type == 2) {
                    $('.preprice').html("");
                    $scope.detail.presentPrice = "免费";
                }
                if (result.data.replyCount > 0) {
                    $('#reply').html('<img src="images/debate.png">' + result.data.replyCount);
                } else {
                    $('#reply').html('<img src="images/debate.png">评论');
                    $('.loadingMore,.comment').css('background', '#efebec');
                }
                if (result.data.collectionNum > 0) {
                    $scope.collectionNum = result.data.collectionNum;
                } else {
                    $scope.collectionNum = '收藏';
                }

                if ($scope.detail.isFollowUp) {
                    $('#collectionImg').attr("src", "images/stored.png").attr("style", "color:#fc724d");
                    $('#collectionNum').attr("style", "color:#fc724d");
                    $('.ng-binding').addClass('ng-binding-srored');
                }

                $('.avatar').attr('src', result.data.createdBy.images[0].imageURL);

                var str = "";
                var imageList = new Array();
                for (var i = 0; i < result.data.images.length; i++) {
                    imageList.push(result.data.images[i].bigImage);
                }
                for (var i = 0; i < result.data.images.length; i++) {
                    str += '<div class="swiper-slide" style="height: ' + screen.width + 'px;"><img onclick="showImage(\'' + imageList + '\',\'' + i + '\')" src="' + result.data.images[i].imageURL + '"> </div>';
                }
                $('.swiper-wrapper').attr('style', 'style="height: ' + screen.width + 'px;"').html(str);

                var mySwiper = new Swiper('.swiper-container', {
                    pagination: '.pagination',
                    paginationClickable: true,
                    onTouchMove: function () {
                        //$('.second-detail .swiper-container .clearfix').hide();
                    }
                });

                var isMore = true;//判断是否有更多数据
                var isfinish = true;//isfinish判断每次数据是否加载完成，完成了才可进行下一次加载

                $scope.ts = 0;
                $scope.getNewData = function (flag) {
                    isfinish = false;
                    ReplyList.get({
                            ts: $scope.ts
                        }, function (result) {
                            $('.loading').hide();
                            $scope.ts = result.data.ts;
                            //if (flag) {
                            //    $scope.replyList = result.data.list;
                            //} else {
                            //    $scope.replyList = $scope.replyList.concat(result.data.list);
                            //}

                            var list = result.data.list;

                            var str = "";
                            for (var i = 0; i < list.length; i++) {
                                var item = list[i];
                                str += '<li class="comment-li clearfix">';
                                str += '<img src="' + item.headImg + '" class="avatar fl" onclick="toPeronalPage1(\'' + item.repliedBy.objId + '\')">';
                                str += '<div class="comment-detail fl" style="word-break: break-all;" id="' + item.objId + ';' + item.repliedBy.objId + '" onclick="replyTo1(\'' + item.repliedBy.nickName + '\',\'' + item.repliedBy.objId + '\',\'' + item.objId + '\')">';
                                if (list[i].replyTo != null && list[i].replyTo != '') {
                                    str += '<span class="me">' + item.repliedBy.nickName + '&nbsp;回复</span>' + item.replyTo.nickName;
                                    str += '<p class="sub-comment">' + item.replyDesc + '</p> ';
                                    str += '<div   class="parent-comment-w" id="' + item.objId + ';' + item.repliedBy.objId + '">';
                                    str += '<span class="irrow"></span>';
                                    str += '<p class="parent-comment">' + item.replyTo.nickName + "说：" + item.quoteId.replyDesc + '</p></div> ';
                                } else {
                                    str += '<span class="name">' + item.repliedBy.nickName + '</span>';
                                    str += ' <p>' + item.replyDesc + '</p>';
                                    str += ''
                                }
                                str += '<span class="info">';
                                str += formatTime(item.dateReplied) + '发布在&nbsp;' + item.community.communityName + '</span> </div> </li>';
                            }

                            $('.comment').html($('.comment').html() + str);

                            isfinish = true;
                            if (result.data.list.length == 0) {
                                isMore = false;
                                $(".loadingMore").html('');
                            }
                        }
                    );
                };

                $scope.getNewData(true);

                $('.wrapper').scroll(function () {
                    if (isMore && isfinish) {
                        var contentHeight = $(".wrapper")[0].scrollHeight;
                        var h = $(".wrapper").height();
                        if ((contentHeight - h - $(this).scrollTop()) <= 105) {
                            $(".loadingMore").html('<img src="images/refresh.gif" />正在加载');
                            //此处为加载下一条的方法
                            $scope.getNewData(false);
                        }
                    } else {
                        $(".loadingMore").html('');
                    }
                }).scroll();
                $('.loading-pop').hide();
            }
        )

    }
]);
detailApp.factory('GoodsDetail', ['$resource',
    function ($resource) {
        //请求接口
        return $resource('http://' + host + '/rest/v1.0/public/market/getGoodsDetail/' + params.goodsId + '/' + screen.width + '?clickSource=' + params.clickSource,
            {}
        );
    }]);

detailApp.factory('ReplyList', ['$resource',
    function ($resource) {
        //请求接口
        return $resource('http://' + host + '/rest/v1.0/public/market/getRepliesByGoodsId/' + params.goodsId,
            {}
        );
    }]);


function formatTime(input) {

    var d = new Date(input), now = new Date(),
        dStamp = d.getTime(), nowStamp = now.getTime();
    if (now.getFullYear() - d.getFullYear() > 0) {
        return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
    } else if ((nowStamp - dStamp) / 1000 < 60) {
        return "刚刚";
    } else if ((nowStamp - dStamp) / 60000 < 60) {
        return Math.floor((nowStamp - dStamp) / 60000) + "分钟前";
    } else if ((nowStamp - dStamp) / 3600000 < 24) {
        return Math.floor((nowStamp - dStamp) / 3600000) + "小时前";
    } else if ((nowStamp - dStamp) / 86400000 >= 1 && (nowStamp - dStamp) / 86400000 <= 3) {
        return Math.floor((nowStamp - dStamp) / 86400000) + "天前";
    } else if ((nowStamp - dStamp) / 86400000 > 3) {
        return (d.getMonth() + 1) + "月" + d.getDate() + "日";
    }
};
